package bmatch.tech.todo.resource;

import bmatch.tech.todo.auth.TokenNeeded;
import bmatch.tech.todo.model.LoginUser;
import bmatch.tech.todo.model.Response;
import bmatch.tech.todo.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;

/**
 * @program:todo
 * @author:LinJinhao
 * @create:2019-01-03 23:26
 **/

@Component
@Path("/main")
public class MainResource {

	//用户服务
	private final UserService userService;

	@Autowired
	public MainResource(UserService userService) {
		this.userService = userService;
	}

	@GET
	@Path("demo")
	public String getInformation(){
		return "Welcome the World！";
	}

	//查询用户信息
	@GET
	@Path("get_user")
	@Produces(MediaType.APPLICATION_JSON)
	public Response getUser(@HeaderParam("userId") String userId){
		Response response = new Response();

		if (StringUtils.isEmpty(userId)){
			response.setStatusCode(Response.RESPONSE_FAIL);
			response.setMessage("用户状态异常，请重新登录！");

			return response;
		}

		LoginUser loginUser = userService.getUserById(userId);
		if (loginUser == null || loginUser.equals("")){
			response.setStatusCode(Response.RESPONSE_FAIL);
			response.setMessage("无此用户！");

			return response;
		}
		response.setStatusCode(Response.RESPONSE_SUCCESS);
		response.setMessage("查询成功");
		response.setOtherData(loginUser);

		return response;
	}

	//通过登录获得userId，定位用户信息位置，更新用户信息
	@POST
	@Path("update")
	@Produces(MediaType.APPLICATION_JSON)
	@TokenNeeded
	public Response updateUser(LoginUser loginUser){
		Response response = new Response();

		if (!userService.updateUser(loginUser)){
			response.setStatusCode(Response.RESPONSE_FAIL);
			response.setMessage("更新失败");

			return response;
		}
		LoginUser updateUser = userService.getUserById(loginUser.getId());
		response.setStatusCode(Response.RESPONSE_SUCCESS);
		response.setMessage("更新成功");
		response.setOtherData(updateUser);

		return response;
	}
}
